package user_service

import (
    "fmt"
    "time"

    "bird/config"
    "bird/internal/api/repository/db_repo"
    "bird/internal/api/repository/db_repo/user_info_repo"
    "bird/internal/pkg/core"
    "bird/pkg/token"
)

func (s *service) GenerateToken(ctx core.Context, phone, vcode string) (error) {
    redisKey := config.RedisKeyPrefixVerifyCode + phone
    acturalVcode, err := s.cache.Get(redisKey)
    fmt.Println("actutal:", acturalVcode, " input:", vcode)
    if err != nil || acturalVcode != vcode {
        return fmt.Errorf("验证码错误")
    }

    qb := user_info_repo.NewQueryBuilder()
    qb.WherePhoneNo(db_repo.EqualPredicate, phone)
    userInfo, err := qb.First(s.db.GetDbR())
    if err != nil {
        return err
    }

    cfg := config.Get().JWT
    accessToken, err := token.New(cfg.Secret).JwtSign(int64(userInfo.Id), userInfo.UserName, cfg.ExpireDuration*time.Hour)
    if err != nil {
        return err
    }
    refreshToken, err := token.New(cfg.Secret).JwtSign(int64(userInfo.Id), userInfo.UserName, cfg.RefreshDuration*time.Hour)
    if err != nil {
        return err
    }

    ctx.SetHeader(config.JwtAccesstoken, accessToken)
    ctx.SetHeader(config.JwtRefreshToekn, refreshToken)

    return nil
}

func (s *service) RefreshToken(ctx core.Context, accessToken, refreshToken string) error {
    cfg := config.Get().JWT
    ret, err := token.New(cfg.Secret).JwtParse(refreshToken)
    if err != nil {
        return err
    }

    accessToken, err = token.New(cfg.Secret).JwtSign(ret.UserID, ret.UserName, cfg.ExpireDuration)
    if err != nil {
        return err
    }
    refreshToken, err = token.New(cfg.Secret).JwtSign(ret.UserID, ret.UserName, cfg.RefreshDuration)
    if err != nil {
        return err
    }

    ctx.SetHeader(config.JwtAccesstoken, accessToken)
    ctx.SetHeader(config.JwtRefreshToekn, refreshToken)

    return nil
}
